<?php
/*
	http://svn.digitalsentience.com/svn/armory/
	
	Copyright (c) 2007, Chris Heald. All rights reserved.
*/


include_once("_db.php");
define("USE_CURL", true);

function getGuildMembers($base_url, $realm, $guild, $minLevel, $clsFilter = false) {
	$url = $base_url . "/guild-info.xml?r=" . urlencode(stripslashes($realm)) . "&n=" . urlencode(stripslashes($guild)) . "&p=1";
	$xml = getArmoryDataXML($url);
	$node = $xml->xpath("/page/guildInfo/guild/members");
	$attr = attribs($node[0]);
	$maxPages = $attr["maxPage"];
	
	$cList = getCharacterList($xml, $minLevel, $clsFilter);
	for($i=2; $i<=$maxPages; $i++) {
		$url = $base_url . "/guild-info.xml?r=" . urlencode(stripslashes($realm)) . "&n=" . urlencode(stripslashes($guild)) . "&p=$i";
		$xml = getArmoryDataXML($url);
		$cList = array_merge($cList, getCharacterList($xml, $minLevel, $clsFilter));
	}
	
	return $cList;
}

function getTeamInfo($base_url, $battlegroup, $teamSize, $teamName) {
	$url = $base_url . "/team-info.xml?b=" . urlencode(stripslashes($battlegroup)) . "&ts=" . $teamSize . "&t=" . urlencode(stripslashes($teamName));
	$xml = getArmoryDataXML($url);
	$n = $xml->xpath("/page/teamInfo/arenaTeam");
	return attribs($n[0]);
}

function getTeamMembers($base_url, $battlegroup, $teamSize, $teamName) {
	$url = $base_url . "/team-info.xml?b=" . urlencode(stripslashes($battlegroup)) . "&ts=" . $teamSize . "&t=" . urlencode(stripslashes($teamName));
	$xml = getArmoryDataXML($url);
	$n = $xml->xpath("/page/teamInfo/arenaTeam/members/character");
	$chars = array();
	foreach($n as $char) {
		$a = attribs($char);
		$chars[$a["name"]] = $char;
	}
	return array_values($chars);
}

function getTeamEmblem($base_url, $battlegroup, $teamSize, $teamName) {
	$url = $base_url . "/team-info.xml?b=" . urlencode(stripslashes($battlegroup)) . "&ts=" . $teamSize . "&t=" . urlencode(stripslashes($teamName));
	$xml = getArmoryDataXML($url);
	$n = $xml->xpath("/page/teamInfo/arenaTeam/emblem");
	$b = $n[0];
	return $b;	
}

function getCachedXML($url) {
	$max_age = 60 * 60 * 11.5;		// 11.5 hours to allow for Coralization race conditions
	$db = getDBCacheConnection();
	$result = mysql_query("select * from cache where hash = '" . md5($url) . "'", $db);
	if(mysql_num_rows($result) == 0) return false;
	$row = mysql_fetch_assoc($result);
	if(time() - strtotime($row["updated_at"]) > $max_age) return false;
	$data = @gzuncompress($row["data"]);
	return $data;
}

function setCachedXML($url, $xml) {
	$db = getDBCacheConnection();
	$result = mysql_query("select * from cache where hash = '" . md5($url) . "'", $db);
	$mu = md5($url);
	$md = mysql_real_escape_string(gzcompress($xml, 9));
	if(mysql_num_rows($result) == 0) {
		$sql = "insert into cache (hash, data, updated_at) values ('$mu', '$md', NOW())";
	} else {
		$sql = "update cache set data = '$md', updated_at = NOW() where hash = '$mu'";
	}
	mysql_query($sql, $db);
	return;
}

function getArmoryDataXML($url) {
	global $xmlDataCache;
	if(!$xmlDataCache[$url]) {
		$data = getCachedXML($url);
		if(!$data) {
			$f = "";
			if(USE_CURL) {
				$ch = curl_init();
				$timeout = 30; // set to zero for no timeout
				$useragent="Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.1) Gecko/20061204 Firefox/2.0.0.1";
				curl_setopt ($ch, CURLOPT_URL, $url);
				curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
				curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
				curl_setopt ($ch, CURLOPT_USERAGENT, $useragent);
				$f = curl_exec($ch);
				curl_close($ch);			
			} else {
				$f = file_get_contents($url);
			}
			$xml = simplexml_load_string($f);
			if($xml)
				setCachedXML($url, $f);
		} else {
			$xml = @simplexml_load_string($data);
			if(!$xml) {
				$f = file_get_contents($url);
				setCachedXML($url, $f);
				$xml = simplexml_load_string($f);
			}
		}
		$xmlDataCache[$url] = $xml;		
	}
	return $xmlDataCache[$url];
}

function attribs($node) {
	$attribs = array();
	if(!$node) {
		throw new Exception("Unable to get node attributes; this likely means that we were unable to retrieve data for the entered realm/guild from the Armory. Please check your input and/or try again later.");
	}
		
	foreach($node->attributes() as $key => $attrib) {
		$attribs[$key] = (string)$attrib;
	}
	return $attribs;
}

function getCharacterList($xml, $minLevel, $class) {
	$cList = array();
	$characters = $xml->xpath("/page/guildInfo/guild/members/character");
	if(sizeof($characters) == 0) {
		echo "<font style='color: #f00; font-weight: bold;'>Warning! No characters found!</font><p />";
	}
	foreach($characters as $character) {
		$attribs = attribs($character);
		if((int)($attribs["level"]) >= $minLevel) {
			if (!$class || $class == $attribs["class"]) {
				$cList[] = array($attribs["name"], $attribs["level"], $attribs["class"]);
			}
		}	
	}
	return $cList;
}

function killCacheEntry($url) {
	$db = getDBCacheConnection();
	$key = md5($url);
	$sql = "delete from cache where hash = '$key'";
	mysql_query($sql, $db);
}

function getCharacterData($base_url, $realm, $name) {
	$url = $base_url . "/character-sheet.xml?r=" . urlencode(stripslashes($realm)) . "&n=" . urlencode(stripslashes($name));
	return getArmoryDataXML($url);
}

function logReferer($output) {
	return;
	$db = getDBCacheConnection();
	$url = preg_replace("/(sid|jsessionid)=[0-9A-F]{32}/i", "", @$_SERVER["HTTP_REFERER"]);
	$hash = md5($url);
	$url = mysql_real_escape_string($url);
	$output = mysql_real_escape_string($output);
	if(!preg_match("/tachyonsix\.com/i", @$_SERVER["HTTP_REFERER"]) && strlen(@$_SERVER["HTTP_REFERER"]) > 0) {
		$sql = "select id from referrer_log where referrer_hash = '$hash' and app = '$output'";
		$result = mysql_query($sql, $db);
		if(mysql_num_rows($result) == 0) {
			$sql = "insert into referrer_log (referrer_url, referrer_hash, hits, created_at, updated_at, app) values (\"$url\", \"$hash\", 1, NOW(), NOW(), '$output')";
			mysql_query($sql, $db);
		} else {
			$row = mysql_fetch_assoc($result);
			$id = $row["id"];
			$sql = "update referrer_log set hits = hits + 1, updated_at = NOW() where id = '$id'";
			mysql_query($sql, $db);
		}
	}
}
?>
